import Vue from 'vue'
import store from '@/store'
import { invokeAsyncAPi } from '@/xz-fn.js'
import copy from 'clipboard-copy'
import PsMessage from '@/components/message/index'
import SnowflakeId from 'snowflake-id'
import { marked } from 'marked'
import hljs from 'highlight.js'
import { invokeAPi } from '@/xz-fn'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
    S: date.getMilliseconds()
  }
  return format.replace(/{([ymdhisaS])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
}
export const getUuid = function (len, radix) {
  var chars = '0123456789abcdefghijklmnopqrstuvwxyz'.split('')
  var uuid = []
  var i
  radix = radix || chars.length

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    // rfc4122, version 4 form
    var r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}
export const ISO8601 = function (d) {
  if (!d) d = new Date()
  return parseTime(d, '{y}-{m}-{d}T{h}:{i}:{s}.{S}')
}
/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime (time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject (url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength (str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray (actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param (json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj (url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ') +
    '"}'
  )
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text (val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge (target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass (element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime (type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}
/**
 * 节流
 * @param {Function} func
 * @param {Number} wait 时间间隔
 * @param {Bolean} immediate 是否立即执行
 * @return {Function}
 */
export const throttle = function (func, wait = 200, immediate = false) {
  let timeout
  return function () {
    if (!timeout) {
      const context = this
      const args = arguments
      if (immediate) {
        func.apply(context, args)
        timeout = setTimeout(function () {
          timeout = null
        }, wait)
      } else {
        timeout = setTimeout(function () {
          timeout = null
          func.apply(context, args)
        }, wait)
      }
    }
  }
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone (source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr (arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString () {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass (ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass (ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass (ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * @param {Array} filterVal
 * @param {Object} jsonData
 * @returns {string}
 */
export function formatJson (filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => {
    if (j === 'timestamp') {
      return parseTime(v[j])
    } else {
      return v[j]
    }
  }))
}

/**
 * @param {*} val
 * @returns {String}
 */
export function getTypeOf (val) {
  return Object.prototype.toString.call(val).toLocaleLowerCase().replace('[object ', '').replace(']', '')
}
export function compareVersion (v1 = '', v2 = '') {
  if (v1 === v2) {
    return 0
  }
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)
  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }
  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])
    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }
  return 0
}

/**
 * 获取当前页面窗口大小尺寸
 * @param {*} routeName 当前路由名称
 */
export function getRouterSize (name) {
  const bigPage = {
    width: 380,
    height: 380,
    smallWidth: 290,
    smallHeight: 290
  }
  const smallPage = {
    width: 380,
    height: 184,
    smallWidth: 290,
    smallHeight: 184
  }
  const bigPagename = ['calendar', 'constellation']
  return bigPagename.includes(name) ? bigPage : smallPage
}

/**
 * 获取屏幕分辨率
 * @param {*} name 当前路由名称
*/
export async function initWindowWidth (name) {
  const res = await invokeAsyncAPi('GetDisplayInfo', {
    WidgetID: name
  })
  if (res && res.DisplayWork) {
    const arr = res.DisplayWork.split(',')
    if (arr.length > 3) {
      return [parseInt(arr[2]) - parseInt(arr[0]), parseInt(arr[3]) - parseInt(arr[1])]
    }
    return []
  }
  return []
}

export function copyFunc (context) {
  copy(context).then(() => {
    PsMessage({ message: '复制成功' })
  }).catch(() => {})
}

// 从文件路径中提取文件名和文件扩展名
export function formatFilePath (path) {
  const parts = path.replaceAll('\\', '/').split('/')
  const fileName = parts[parts.length - 1]
  const lastDotIndex = fileName.lastIndexOf('.')
  const name = fileName.substring(0, lastDotIndex)
  const ext = (fileName.substring(lastDotIndex + 1) || '').toLowerCase()
  return { name, ext, full: name + '.' + ext }
}

/**
 * 格式话模型对应的图标类型
 * @param model
 * @returns
 */
// eslint-disable-next-line sonarjs/cognitive-complexity
export function formatModelTypeIcon (model) {
  if (!model) return ''
  const type = encodeURI(model.toUpperCase())
  if (type.includes('ERNIE') || type.includes(encodeURI('文心一言'))) return 'model-baidu'
  if (type.includes('GLM')) return 'model-glm'
  if (type.includes('GPT-3')) return 'model-gpt3'
  if (type.includes('GPT-4')) return 'model-gpt4'
  if (type.includes('QIANFAN')) return 'model-qianfan'
  if (type.includes('CHATDOC')) return 'model-chatdoc'
  // if (type.includes('TXYZ')) return 'model-txyz'
  if (type.includes('MOONSHOT') || type.includes('KIMI')) return 'model-moonshot'
  if (type.includes('BAIDUWENCHAIN') || type.includes(encodeURI('百度文库'))) return 'model-wenku'
  if (type.includes('TXYZ') || type.includes(encodeURI('自研'))) return 'model-eva'
  if (type.includes('customgpt') || type.includes(encodeURI('网页总结'))) return 'model-eva'
  return ''
}

export function getFaviconFromLink (url) {
  try {
    const link = new URL(url)
    return link.origin + '/favicon.ico'
  } catch (e) {
    return ''
  }
}
const snowflakeId = new SnowflakeId()
export function getSnowflakeId () {
  return snowflakeId.generate()
}
export function formatSumarizeType (doc) {
  if (doc.url) return 'link'
  return 'pdf'
}

export function isSensitiveCode (code) {
  if (!code) return false
  return [1007, 1004].includes(code)
}
export function isDifyRetry (code) {
  if (!code) return false
  return [1020, 1021, 2022].includes(code)
}

export const awaitNextick = (time) =>
  new Promise((resolve) => {
    if (!time) {
      Vue.nextTick(() => {
        resolve(null)
      })
      return
    }
    Vue.nextTick(() => {
      setTimeout(() => {
        resolve(null)
      }, time * 1000)
    })
  })

export function isHasChinese (str) {
  const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
  return reg.test(str)
}

const renderer = {
  code (text, lang, escaped) {
    const language = (lang || '').match(/\S*/)?.[0] || ''
    const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'
    const codeStr = escaped
      ? hljs.highlight(validLanguage, text).value
      : hljs.highlightAuto(text).value
    return `<pre class="pre__code"><div class="pre__code__header"><span>${validLanguage === 'plaintext' ? '' : validLanguage}</span><svg class="svg-icon fs-16 copy-btn" aria-hidden="true" title=""><use xlink:href="#icon-copy-btn"></use></svg></div><code class="hljs ${validLanguage}">${codeStr}</code></pre>`
  }
}
export const rendererMD = marked.use({ renderer })

const runCallback = (obj, appName) => { // dll 和 yueshu 暂时没有上报，使用xz的上报
  const config = obj[appName]
  if (config && typeof config === 'function') {
    config()
  }
  if (typeof config === 'object' && config.callback && typeof config.callback === 'function') {
    config.callback()
  }
}

// 跳转登录
export const gotoLogin = (obj) => {
  const appName = process.env.VUE_APP_NAME
  if (appName === 'xz') {
    invokeAPi('OpenUserCenter')
    invokeAPi('HtmlClickReport', { ReportID: 8504 })
    invokeAPi('xz_set_stat_id', 8504)
  } else if (['yueshu', 'dll'].includes(appName)) {
    invokeAPi('xz_switch_dialog', 'XZDesktopLogin', true, process.env.VUE_APP_WINDOW_NAME, process.env.VUE_APP_WINDOW_NAME)
    invokeAPi('HtmlClickReport', { ReportID: 8504 })
    invokeAPi('xz_set_stat_id', 8504)
  }
  runCallback(obj, 'xz')
}

const gotoMemberInXz = (action, obj) => {
  const params = {
    action: action
  }
  if (obj['xz'] && typeof obj['xz'] === 'object' && obj['xz'].stat_id) {
    params.stat_id = obj['xz'].stat_id
  }
  params.business = 'buyMember'
  if (store.getters.appInfo.appID === 111) {
    invokeAPi('OpenUserCenter', encodeURIComponent(JSON.stringify(params)))
  } else {
    invokeAPi(
      'UpgradeMembership',
      encodeURIComponent(JSON.stringify({ // encodeURIComponent解决跨端时客户端对字符串中的“/”截断问题
        toWinId: 'XZDesktopOrderVIP',
        ...params
      }))
    )
  }
}

const gotoMemberInDll = (str) => {
  invokeAPi('xz_switch_dialog', 'XZDesktopOrderVIP', true, str, process.env.VUE_APP_WINDOW_NAME)
}

// 跳转会员
export const gotoMember = (obj) => {
  const appName = process.env.VUE_APP_NAME
  if (appName === 'xz') {
    gotoMemberInXz('vip', obj)
  } else if (['yueshu', 'dll', 'repairmaster'].includes(appName)) {
    gotoMemberInDll(process.env.VUE_APP_WINDOW_NAME)
  }
  runCallback(obj, 'xz')
}

// 跳转购买token/能量
export const gotoUserToken = (obj) => {
  const appName = process.env.VUE_APP_NAME
  if (appName === 'xz') {
    gotoMemberInXz('jgb', obj)
  } else if (appName === 'yueshu') {
    this.$xz('xz_jump_buy_token')
  } else if (['dll', 'repairmaster'].includes(appName)) {
    gotoMemberInDll(JSON.stringify({ type: 'energy' }))
  }
  runCallback(obj, 'xz')
}

// 跳转能量规则
export const gotoEnergyRules = (obj) => {
  const appName = process.env.VUE_APP_NAME
  if (appName === 'xz') {
    gotoMemberInXz('seeFnPrice', obj)
  } else if (appName === 'yueshu') {

  } else if (['dll', 'repairmaster'].includes(appName)) {
    gotoMemberInDll(JSON.stringify({ type: 'energy', position: 'energy-rule' }))
  }
  runCallback(obj, 'xz')
}

// 跳转能量消费记录
export const gotoEnergyRecord = (obj) => {
  const appName = process.env.VUE_APP_NAME
  if (appName === 'xz') {
    invokeAPi('OpenUserCenter', encodeURIComponent(JSON.stringify({ to: '/orderlist', status: 3 })))
  } else if (appName === 'yueshu') {

  } else if (['dll', 'repairmaster'].includes(appName)) {
    invokeAPi('xz_switch_dialog', 'XZDesktopUserCenter', true, JSON.stringify({ status: 'ai-record', page: 'orderlist' }), process.env.VUE_APP_WINDOW_NAME)
  }
  runCallback(obj, 'xz')
}
